@file:Suppress("unused")

package com.csw.android.dev_utils.result

import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
import kotlin.collections.HashMap

/**
 * 通过Fragment解耦onActivityResult实现，可用于所有需要解耦onActivityResult的场景，
 * 比如获取第三方登录结果，拍照，编辑图片，选取系统图片等等。
 */
object OnActivityResultHelper {
    private val HELPER_FRAGMENT_TAG = UUID.randomUUID().toString()

    /**
     * 跳转界面，获取返回结果
     * @param fragmentManager fragment管理器
     * @param intent 跳转的intent
     * @param data 界面传递的数据
     * @param callback 界面返回结果时回调接口对象
     */
    fun startActivityForResult(
        fragmentManager: FragmentManager,
        intent: Intent,
        data: Bundle?,
        callback: Callback
    ) {
        startActivityForResult(fragmentManager, ActivityRequestTask(intent, data, callback))
    }

    /**
     * 跳转界面，获取返回结果
     * @param fragmentManager fragment管理器
     * @param activityRequestTask 任务封装
     */
    fun startActivityForResult(
        fragmentManager: FragmentManager,
        activityRequestTask: ActivityRequestTask
    ) {
        val fragment = fragmentManager.findFragmentByTag(HELPER_FRAGMENT_TAG)
        if (fragment is HelperFragment) {
            fragment
        } else {
            HelperFragment()
        }.run {
            if (!isAdded) {
                fragmentManager.beginTransaction().add(this, HELPER_FRAGMENT_TAG)
                    .commitNowAllowingStateLoss()
            } else if (isDetached) {
                fragmentManager.beginTransaction().attach(this)
                    .commitNowAllowingStateLoss()
            }
            startTask(activityRequestTask)
        }
    }

    class HelperFragment : Fragment() {
        private val maxTask = 1000//最多同时存在的任务数量
        private val requestCodeProvider = AtomicInteger(0)
        private val taskHolder = HashMap<Int, ActivityRequestTask>()

        fun startTask(task: ActivityRequestTask) {
            if (taskHolder.size > maxTask) {
                return
            }
            var code: Int
            do {
                code = requestCodeProvider.incrementAndGet()
                if (code >= 0xFFFF) {
                    requestCodeProvider.set(0)
                    code = requestCodeProvider.incrementAndGet()
                }
            } while (taskHolder[code] != null)
            taskHolder[code] = task
            startActivityForResult(task.requestIntent, code)
        }

        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            super.onActivityResult(requestCode, resultCode, data)
            taskHolder.remove(requestCode)?.onActivityResult(resultCode, data)
        }
    }

}